package com.newsee.remote.sapcenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newsee.remote.common.database.entity.ShSapcostcenter;
import com.newsee.remote.common.database.mapper.ShSapcostcenterMapper;
import com.newsee.remote.common.dto.costcenter.CostCenterDTO;
import com.newsee.remote.common.dto.costcenter.CostReqBaseInfoDTO;
import com.newsee.remote.common.dto.costcenter.CostReqItemDTO;
import com.newsee.remote.common.dto.sapcenter.budgetdepartment.BudgetDepDTO;
import com.newsee.remote.common.dto.sapcenter.budgetdepartment.BudgetDepReqItemDTO;
import com.newsee.remote.common.dto.sapcenter.companycode.CompanyCodeDTO;
import com.newsee.remote.common.dto.sapcenter.companycode.CompanyReqItemDTO;
import com.newsee.remote.common.dto.sapcenter.costcenter.CostCentDTO;
import com.newsee.remote.common.dto.sapcenter.costcenter.CostCenterReqItemDTO;
import com.newsee.remote.common.dto.sapcenter.organization.OrgReqItemDTO;
import com.newsee.remote.common.dto.sapcenter.organization.OrganizationDTO;
import com.newsee.remote.common.dto.sapcenter.profitcenter.ProfitCenterDTO;
import com.newsee.remote.common.dto.sapcenter.profitcenter.ProfitReqItemDTO;
import com.newsee.remote.common.enumeration.SapOrganizationTypeEnum;
import com.newsee.remote.common.enumeration.SrmRspStatusCodeEnum;
import com.newsee.remote.common.utils.ecache.ConcurrentHashMapCacheUtil;
import com.newsee.remote.common.utils.tools.DateUtils;
import com.newsee.remote.common.vo.costcenter.CostCenterVO;
import com.newsee.remote.common.vo.supplier.EResponseVO;
import com.newsee.remote.common.vo.supplier.MessageVO;
import com.newsee.remote.common.vo.supplier.RspBaseInfoVO;
import com.newsee.remote.common.vo.supplier.RspItemVO;
import com.newsee.remote.sapcenter.service.IShSapcostcenterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liangzhichen
 * @since 2019-11-05
 */
@Slf4j
@Service
public class ShSapcostcenterServiceImpl extends ServiceImpl<ShSapcostcenterMapper, ShSapcostcenter> implements IShSapcostcenterService {

    @Override
    public CostCenterVO acceptSapCenter(CostCenterDTO centerDTO) {
        CostCenterVO vo = new CostCenterVO();

        if (!checkData(centerDTO)) {
            generatorRspBaseInfo(centerDTO.getI_REQUEST().getREQ_BASEINFO(), vo, SrmRspStatusCodeEnum.SEND_MESSAGE_ERROR.getCode());
            return vo;
        }

        try {
            //srm提供的供应商报文
            List<CostReqItemDTO> heads = centerDTO.getI_REQUEST().getMESSAGE().getREQ_ITEM();

            for (CostReqItemDTO head : heads) {
                //唯一标识
                String costCode = head.getCostCode();
                boolean lock = ConcurrentHashMapCacheUtil.lock(costCode);
                if (!lock){
                    continue;
                }
                ShSapcostcenter shSapcostcenter = getOne(new QueryWrapper<ShSapcostcenter>().eq("CostCode", costCode));

                //新增
                if (null == shSapcostcenter) {
                    shSapcostcenter = new ShSapcostcenter();
                    shSapcostcenter.setCreateTime(LocalDateTime.now());
                } else {
                    shSapcostcenter.setUpdateTime(LocalDateTime.now());
                }
                shSapcostcenter.setCostCode(head.getCostCode());
                shSapcostcenter.setCostName(head.getCostName());
                shSapcostcenter.setParentCostCode(head.getParentCostCode());
                shSapcostcenter.setOrganizationType(head.getOrganizationType());
                shSapcostcenter.setTaxCompanyType(head.getTaxCompanyType());
                shSapcostcenter.setCostState(head.getCostState());
                saveOrUpdate(shSapcostcenter);
                ConcurrentHashMapCacheUtil.unLock(costCode);
            }
            generatorRspBaseInfo(centerDTO.getI_REQUEST().getREQ_BASEINFO(), vo, SrmRspStatusCodeEnum.HANDLE_SUCCESS.getCode());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("组织架构同步出错：" + e.getMessage());
            generatorRspBaseInfo(centerDTO.getI_REQUEST().getREQ_BASEINFO(), vo, SrmRspStatusCodeEnum.INTERNAL_ERROR.getCode());
            return vo;
        }
        return vo;
    }

    @Override
    public CostCenterVO acceptOrganization(OrganizationDTO dto) {
        CostCenterVO vo = new CostCenterVO();

        try {
            //srm提供的供应商报文
            List<OrgReqItemDTO> heads = dto.getI_REQUEST().getMESSAGE().getREQ_ITEM();

            for (OrgReqItemDTO head : heads) {
                //唯一标识
                String costCode = head.getHCODE();
                boolean lock = ConcurrentHashMapCacheUtil.lock(costCode);
                if (!lock){
                    continue;
                }
                ShSapcostcenter shSapcostcenter = getOne(new QueryWrapper<ShSapcostcenter>().eq("CostCode", costCode));

                //新增
                if (null == shSapcostcenter) {
                    shSapcostcenter = new ShSapcostcenter();
                    shSapcostcenter.setCreateTime(LocalDateTime.now());
                } else {
                    shSapcostcenter.setUpdateTime(LocalDateTime.now());
                }
                shSapcostcenter.setCostCode(costCode);
                shSapcostcenter.setCostName(head.getHNAME());
                shSapcostcenter.setParentCostCode(head.getNIDUP());
                shSapcostcenter.setOrganizationType(SapOrganizationTypeEnum.getTextByCode(head.getNTYPE()));
                //在用
//                if (null != head.getIS_FLAG() && "X".equals(head.getIS_FLAG())) {
//                    shSapcostcenter.setCostState(0);
//                } else {
//                    shSapcostcenter.setCostState(1);
//                }
                shSapcostcenter.setCostState(0);
                saveOrUpdate(shSapcostcenter);
                ConcurrentHashMapCacheUtil.unLock(costCode);
            }
            generatorRspBaseInfo(dto.getI_REQUEST().getREQ_BASEINFO(), vo, SrmRspStatusCodeEnum.HANDLE_SUCCESS.getCode());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("接收SAP组织架构出错：" + e.getMessage());
            generatorRspBaseInfo(dto.getI_REQUEST().getREQ_BASEINFO(), vo, SrmRspStatusCodeEnum.INTERNAL_ERROR.getCode());
            return vo;
        }
        return vo;
    }

    @Override
    public CostCenterVO acceptCompanyCode(CompanyCodeDTO dto) {
        CostCenterVO vo = new CostCenterVO();

        try {
            //srm提供的供应商报文
            List<CompanyReqItemDTO> heads = dto.getI_REQUEST().getMESSAGE().getREQ_ITEM();

            for (CompanyReqItemDTO head : heads) {
                //唯一标识
                String costCode = head.getBUKRS();
                boolean lock = ConcurrentHashMapCacheUtil.lock(costCode);
                if (!lock){
                    continue;
                }
                ShSapcostcenter shSapcostcenter = getOne(new QueryWrapper<ShSapcostcenter>().eq("CostCode", costCode));

                //新增
                if (null == shSapcostcenter) {
                    log.error("接收公司代码出错：未找到对应的组织结构,对应的costCode为 {}", head.getBUKRS());
                } else {
                    shSapcostcenter.setUpdateTime(LocalDateTime.now());
                    //在用
                    if (null != head.getZFLAG() && "X".equals(head.getZFLAG())) {
                        shSapcostcenter.setTaxCompanyType("X");
                    } else {
                        shSapcostcenter.setTaxCompanyType("");
                    }
                    saveOrUpdate(shSapcostcenter);
                }
                ConcurrentHashMapCacheUtil.unLock(costCode);
            }
            generatorRspBaseInfo(dto.getI_REQUEST().getREQ_BASEINFO(), vo, SrmRspStatusCodeEnum.HANDLE_SUCCESS.getCode());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("接收公司代码出错：" + e.getMessage());
            generatorRspBaseInfo(dto.getI_REQUEST().getREQ_BASEINFO(), vo, SrmRspStatusCodeEnum.INTERNAL_ERROR.getCode());
            return vo;
        }
        return vo;

    }

    @Override
    public CostCenterVO acceptProfitCenter(ProfitCenterDTO dto) {
        CostCenterVO vo = new CostCenterVO();

        try {
            //srm提供的供应商报文
            List<ProfitReqItemDTO> heads = dto.getI_REQUEST().getMESSAGE().getREQ_ITEM();

            for (ProfitReqItemDTO head : heads) {
                //唯一标识
                String costCode = head.getPRCTR();
                boolean lock = ConcurrentHashMapCacheUtil.lock(costCode);
                if (!lock){
                    continue;
                }
                ShSapcostcenter shSapcostcenter = getOne(new QueryWrapper<ShSapcostcenter>().eq("CostCode", costCode));

                //新增
                if (null == shSapcostcenter) {
                    shSapcostcenter = new ShSapcostcenter();
                    shSapcostcenter.setCreateTime(LocalDateTime.now());
                } else {
                    shSapcostcenter.setUpdateTime(LocalDateTime.now());
                }
                shSapcostcenter.setCostCode(costCode);
                shSapcostcenter.setCostName(head.getKTEXT());
                shSapcostcenter.setParentCostCode(head.getBUKRS());
                shSapcostcenter.setOrganizationType("利润中心");
                //在用
//                if (null != head.getIS_FLAG() && "X".equals(head.getIS_FLAG())) {
//                    shSapcostcenter.setCostState(0);
//                } else {
//                    shSapcostcenter.setCostState(1);
//                }
                shSapcostcenter.setCostState(0);
                saveOrUpdate(shSapcostcenter);
                ConcurrentHashMapCacheUtil.unLock(costCode);
            }
            generatorRspBaseInfo(dto.getI_REQUEST().getREQ_BASEINFO(), vo, SrmRspStatusCodeEnum.HANDLE_SUCCESS.getCode());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("接收利润中心信息出错：" + e.getMessage());
            generatorRspBaseInfo(dto.getI_REQUEST().getREQ_BASEINFO(), vo, SrmRspStatusCodeEnum.INTERNAL_ERROR.getCode());
            return vo;
        }
        return vo;

    }

    @Override
    public CostCenterVO acceptCostCenter(CostCentDTO dto) {
        CostCenterVO vo = new CostCenterVO();

        try {
            //srm提供的供应商报文
            List<CostCenterReqItemDTO> heads = dto.getI_REQUEST().getMESSAGE().getREQ_ITEM();

            for (CostCenterReqItemDTO head : heads) {
                //唯一标识
                String costCode = head.getKOSTL();
                boolean lock = ConcurrentHashMapCacheUtil.lock(costCode);
                if (!lock){
                    continue;
                }
                ShSapcostcenter shSapcostcenter = getOne(new QueryWrapper<ShSapcostcenter>().eq("CostCode", costCode));

                //新增
                if (null == shSapcostcenter) {
                    shSapcostcenter = new ShSapcostcenter();
                    shSapcostcenter.setCreateTime(LocalDateTime.now());
                } else {
                    shSapcostcenter.setUpdateTime(LocalDateTime.now());
                }
                shSapcostcenter.setCostCode(costCode);
                shSapcostcenter.setCostName(head.getKTEXT());
                shSapcostcenter.setParentCostCode(head.getPRCTR());
                shSapcostcenter.setOrganizationType("成本中心");
                //在用
//                if (null != head.getIS_FLAG() && "X".equals(head.getIS_FLAG())) {
//                    shSapcostcenter.setCostState(0);
//                } else {
//                    shSapcostcenter.setCostState(1);
//                }
                shSapcostcenter.setCostState(0);
                saveOrUpdate(shSapcostcenter);
                ConcurrentHashMapCacheUtil.unLock(costCode);
            }
            generatorRspBaseInfo(dto.getI_REQUEST().getREQ_BASEINFO(), vo, SrmRspStatusCodeEnum.HANDLE_SUCCESS.getCode());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("接收成本中心信息出错：" + e.getMessage());
            generatorRspBaseInfo(dto.getI_REQUEST().getREQ_BASEINFO(), vo, SrmRspStatusCodeEnum.INTERNAL_ERROR.getCode());
            return vo;
        }
        return vo;

    }

    @Override
    public CostCenterVO acceptBudgetDep(BudgetDepDTO dto) {
        CostCenterVO vo = new CostCenterVO();

        try {
            //srm提供的供应商报文
            List<BudgetDepReqItemDTO> heads = dto.getI_REQUEST().getMESSAGE().getREQ_ITEM();

            for (BudgetDepReqItemDTO head : heads) {
                //唯一标识
                String costCode = head.getBG_DEPT();
                boolean lock = ConcurrentHashMapCacheUtil.lock(costCode);
                if (!lock){
                    continue;
                }
                ShSapcostcenter shSapcostcenter = getOne(new QueryWrapper<ShSapcostcenter>().eq("CostCode", costCode));

                //新增
                if (null == shSapcostcenter) {
                    shSapcostcenter = new ShSapcostcenter();
                    shSapcostcenter.setCreateTime(LocalDateTime.now());
                } else {
                    shSapcostcenter.setUpdateTime(LocalDateTime.now());
                }
                shSapcostcenter.setCostCode(costCode);
                shSapcostcenter.setCostName(head.getBG_DEPTN());
                shSapcostcenter.setParentCostCode(head.getPARNT());
                shSapcostcenter.setOrganizationType("预算部门");
                //在用
//                if (null != head.getIS_FLAG() && "X".equals(head.getIS_FLAG())) {
//                    shSapcostcenter.setCostState(0);
//                } else {
//                    shSapcostcenter.setCostState(1);
//                }

                shSapcostcenter.setCostState(0);
                saveOrUpdate(shSapcostcenter);
                ConcurrentHashMapCacheUtil.unLock(costCode);
            }
            generatorRspBaseInfo(dto.getI_REQUEST().getREQ_BASEINFO(), vo, SrmRspStatusCodeEnum.HANDLE_SUCCESS.getCode());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("接收预算部门信息出错：" + e.getMessage());
            generatorRspBaseInfo(dto.getI_REQUEST().getREQ_BASEINFO(), vo, SrmRspStatusCodeEnum.INTERNAL_ERROR.getCode());
            return vo;
        }
        return vo;
    }

    private boolean checkData(CostCenterDTO centerDTO) {
        //默认成功
        Boolean flag = true;
        return true;
    }

    /**
     * 生成响应报文基础信息名称
     *
     * @param reqBaseinfo 请求
     * @param vo          返回
     */
    private void generatorRspBaseInfo(CostReqBaseInfoDTO reqBaseinfo, CostCenterVO vo, String rspStatsCode) {

        //-------封装返回对象--------
        //响应报文根节点名称
        EResponseVO eResponseVO = new EResponseVO();
        vo.setE_RESPONSE(eResponseVO);

        //响应报文基础信息名称
        RspBaseInfoVO rspBaseInfoVO = new RspBaseInfoVO();
        eResponseVO.setRSP_BASEINFO(rspBaseInfoVO);
        //接收系统返回消息，产生的 TRACE_ID，消息的唯一标识
        rspBaseInfoVO.setRSP_TRACE_ID(UUID.randomUUID().toString().replace("-", ""));
        //响应请求 TRACE_ID
        rspBaseInfoVO.setRSP_REQ_TRACEID(reqBaseinfo.getREQ_TRACE_ID());
        //报文发送时间，14位数字
        rspBaseInfoVO.setRSP_SEND_TIME(Long.valueOf(DateUtils.format(new Date(), DateUtils.DATE_PATTERN_FULL)));
        //发送方系统标识
        rspBaseInfoVO.setRSP_SRC_SYS(reqBaseinfo.getREQ_SRC_SYS());
        //接收方系统标识:
        rspBaseInfoVO.setRSP_TAR_SYS("BS-WY-RFWZ");
        //PO 或 ESB 上定义的SI名称，由PO或ESB/顾问提供
        rspBaseInfoVO.setRSP_SERVER_NAME(reqBaseinfo.getREQ_SERVER_NAME());
        //业务系统流水号或业务唯一编号，从请求报文中获取
        rspBaseInfoVO.setRSP_BSN_ID(reqBaseinfo.getREQ_BSN_ID());
        //接口处理状态代码
        rspBaseInfoVO.setRSP_STATUS_CODE(rspStatsCode);

        //给srm返回的信息
        MessageVO messageVO = new MessageVO();
        RspItemVO rspItemVO = new RspItemVO();
        eResponseVO.setMESSAGE(messageVO);
        messageVO.setRSP_ITEM(rspItemVO);
        rspItemVO.setRSP_STATUS_CODE(rspStatsCode);
        rspItemVO.setRSP_STATUS_MSG(SrmRspStatusCodeEnum.getTextByCode(rspStatsCode));
    }
}
